package com.nginx.web.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nginx.web.domain.HttpInfoQo;
import com.nginx.web.domain.UpstreamServerQo;
import com.nginx.web.entity.UpstreamInfo;
import com.nginx.web.entity.UpstreamServer;
import com.nginx.web.mapper.UpstreamServerMapper;
import com.nginx.web.service.UpstreamServerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nginx.web.util.ApiUtil;
import com.nginx.web.util.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lyc
 * @since 2025-01-16
 */
@Service
public class UpstreamServerServiceImpl extends ServiceImpl<UpstreamServerMapper, UpstreamServer> implements UpstreamServerService {

    @Autowired
    private ConfInfoServiceImpl confInfoService;
    @Autowired
    private ConfFileServiceImpl confFileService;

    public Page<UpstreamServer> listUpstreamServerInfo(UpstreamServerQo qo) {
        Page<UpstreamServer> page = new Page<>(qo.getPage() , qo.getLimit());
        LambdaQueryWrapper<UpstreamServer> wrapper = Wrappers.lambdaQuery(UpstreamServer.class);
        if(qo.getUpstreamInfoId() != null){
            wrapper.eq(UpstreamServer::getUpstreamInfoId , qo.getUpstreamInfoId());
        }
        page(page , wrapper);
        return page;
    }

    public void updateUpstreamServerInfo(UpstreamServer upstreamServer) {
        updateById(upstreamServer);
    }

    public void updateUpstreamServerStatus(UpstreamServer upstreamServer) {
        updateById(upstreamServer);
        confInfoService.writeConfInfo();
        String check = confFileService.checkNginx();
        String reload = confFileService.reloadNginx();
        if(!StrUtil.contains(check , "success") || StrUtil.isNotEmpty(reload)){
            ApiUtil.back(ResultEnum.ERROR , check + "\n" + reload);
        }
    }
}
